#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

import os
from gupiao.mypkg import gupiaodb
from gupiao.mypkg import twj9018
from datetime import datetime


class GupiaoPipeline(object):

    def __init__(self):

        _up = os.environ.get('EXPECT_UP')
        _low = os.environ.get('EXPECT_LOW')

        self.EXPECT_UP = _up if _up else 13.5
        self.EXPECT_LOW = _low if _low else 7.5

    def process_item(self, item, spider):

        name = item['name']
        price = item['price']

        # 涨到预期值
        if float(price) >= float(self.EXPECT_UP):
            _content = """
            Hi twj:

                Good News, The price of {0} rise to {1} expect[{2}],
            Please dispose the message as soon as possible.

                                            From: aliyun by scrapy
                                            Date: {3}
            """.format(spider.name, price, self.EXPECT_UP,
                       datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

            _subject = '{0} rise to {1} expect[{2}]'.format(spider.name, price,
                                                            self.EXPECT_UP)
            twj9018.main(_subject, _content)

        # 跌到预期值
        elif float(price) <= float(self.EXPECT_LOW):
            _content = """
            Hi twj:

                Good News, The price of {0} fall to {1} expect[{2}],
            Please dispose the message as soon as possible.

                                            From: aliyun by scrapy
                                            Date: {3}
            """.format(spider.name, price, self.EXPECT_LOW,
                       datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

            _subject = '{0} fall to {1} expect[{2}]'.format(spider.name, price,
                                                            self.EXPECT_LOW)
            twj9018.main(_subject, _content)

        session = gupiaodb.get_session()
        try:
            _id = session.query(gupiaodb.Gupiao).all()[-1]
        except Exception:
            new_id = 1
        else:
            new_id = _id.id + 1

        instance = gupiaodb.Gupiao(id=new_id, name=name, price=price)

        session.add(instance)
        session.commit()

        return item
